﻿/*
创建人：zhangrj
日期：2023-08-07
描述：热表自动开卡页面维护js
*/
var page = {
    rootPath: getRootPath(), //网站根路径
    url: getRootPath() + "/Ashx/ReBiaoConainer/RBContainerAutoStartHandler.ashx",
    //初始化页面
    init: function () {
        page.bind();
        notCardPage.init();
        beCardPage.init();
        errorPage.init();
    },
    //页面事件绑定
    bind: function () {
        //查询按钮
        $('#btnSearch').on("click", function () {
            page.clearPage(false, true, true, true);
            var tab = $('#tt').tabs('getSelected');
            var index = $('#tt').tabs('getTabIndex', tab);
            switch (index) {
                case 0: //未开卡查询
                    notCardPage.pageNumber = 1;
                    notCardPage.searchData();
                    break;
                case 1: //已开卡查询
                    beCardPage.pageNumber = 1;
                    beCardPage.searchData();
                    break;
                case 2: //异常记录查询
                    errorPage.pageNumber = 1;
                    errorPage.searchData();
                    break;
                default:
                    displayMessage("未知功能", false);
                    break;
            }
        });
        //清除按钮
        $('#btnReset').on("click", function () {
            page.clearPage(true, true, true, true);
        });
        //切换
        $('#tt').tabs({
            onSelect: function (title, index) {
                switch (title) {
                    case "未开卡":
                        notCardPage.showSearch();
                        break;
                    case "已开卡":
                        beCardPage.showSearch();
                        break;
                    case "异常记录":
                        errorPage.showSearch();
                        break;
                    default:
                        displayMessage("未知功能", false);
                        break;
                }
            }
        });
    },
    //禁用页面所有按钮
    disableBtn: function () {
        $("body").find(".easyui-linkbutton").each(function () {
            $(this).linkbutton('disable');
        });
        $('#tt').tabs('disableTab', 0);
        $('#tt').tabs('disableTab', 1);
        $('#tt').tabs('disableTab', 2);
        $("#mask").show();
    },
    //启用页面所有按钮
    enableBtn: function () {
        $("body").find(".easyui-linkbutton").each(function () {
            $(this).linkbutton('enable');
        });
        $('#tt').tabs('enableTab', 0);
        $('#tt').tabs('enableTab', 1);
        $('#tt').tabs('enableTab', 2);
        $("#mask").hide();
    },
    //清除页面（查询区域，列表区域，填写区域，是否清空消息，是否重置分页参数）
    clearPage: function (query, list, msg, pager) {
        if (query) {
            $("#queryForm").find(".easyui-textbox").each(function () {
                $(this).textbox("clear");
            });
            $("#queryForm").find(".easyui-datebox").each(function () {
                $(this).datebox("clear");
            });
        }
        if (list) {
            clearEasyuiDataGrid("gdContainerInfoNot"); //清空列表
            clearEasyuiDataGrid("gdContainerInfoOff"); //清空列表
            clearEasyuiDataGrid("gdContainerInfoError"); //清空列表
        }
        if (msg) {
            clearMessage();
        }
        if (pager) {
            //未开卡页面分页参数重置
            $("#progressBar").hide();
            $("#gdContainerInfoNot").datagrid("hideColumn", "IsError");
            $("#gdContainerInfoNot").datagrid("hideColumn", "Message");
            notCardPage.pageNumber = 1; notCardPage.pageTotal = 0
            $('#ppNot').pagination('refresh', {
                total: notCardPage.pageTotal,
                pageSize: notCardPage.pageSize,
                pageNumber: notCardPage.pageNumber
            });
            //已开卡页面分页参数重置
            beCardPage.pageNumber = 1; beCardPage.pageTotal = 0
            $('#ppEnd').pagination('refresh', {
                total: beCardPage.pageTotal,
                pageSize: beCardPage.pageSize,
                pageNumber: beCardPage.pageNumber
            });
            //出错页面分页参数重置
            errorPage.pageNumber = 1; errorPage.pageTotal = 0
            $('#ppError').pagination('refresh', {
                total: errorPage.pageTotal,
                pageSize: errorPage.pageSize,
                pageNumber: errorPage.pageNumber
            });
        }
    },
    //post数据（路径，参数，是否异步，成功返回方法）
    post: function (url, param, async, callback) {
        $.ajax({
            type: "Post",
            url: url,
            data: param,
            cashe: false,
            async: async,
            dataType: "json",
            beforeSend: function () {
                $.messager.progress({ text: '', msg: '处理中...' });
            },
            success: function (data) {
                $.messager.progress('close');
                callback(data);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $.messager.progress('close');
                displayMessage(XMLHttpRequest.responseText, false);
                $("body").find(".easyui-linkbutton").each(function () {
                    $(this).linkbutton('enable');
                });
            }
        });
    }
};
//未开卡
var notCardPage = {
    selectedRows: {}, //选择的数据
    progress: 0, //总进度
    pageTotal: 0,
    pageSize: 20,
    pageNumber: 1,
    //初始化页面
    init: function () {
        notCardPage.bind();
        NewcustomizedEasyuiPagination('ppNot'); //定制化分页
    },
    //页面事件绑定
    bind: function () {
        //列表加载
        $("#gdContainerInfoNot").datagrid({
            onLoadSuccess: function (data) {
                $('#ppNot').pagination('refresh', {	// 改变选项，并刷新分页栏信息
                    total: notCardPage.pageTotal,
                    pageSize: notCardPage.pageSize,
                    pageNumber: notCardPage.pageNumber
                });
                NewcustomizedEasyuiPagination('ppNot'); //定制化分页
            },
            columns: [[
                 { field: 'ck', title: '选择', checkbox: true },
                 { field: 'IsError', title: '状态', width: 80, hidden: true },
                 { field: 'Message', title: '消息', width: 200, hidden: true },
                 { field: 'MFGORDERNAME', title: '订单号', width: 120 },
                 { field: 'CONTAINERNAME', title: '批次', width: 180 },
                 { field: 'DESCRIPTION', title: '零件名称', width: 150 },
                 { field: 'CONTAINERTYPENAME', title: '批次类型', width: 80 },
                 { field: 'APSQTY', title: '计划数', width: 80 },
                 { field: 'QTY', title: '在制数', width: 80 },
                 { field: 'WORKFLOWINFO', title: '工艺路线及版本', width: 160 },
                 { field: 'WORKFLOWSTEPNAME', title: '工序', width: 150 },
                 { field: 'SUBWORKFLOWINFO', title: '关联子工艺', width: 180 },
                 { field: 'NEWSUBWORKFLOWINFO', title: '最新版子工艺', width: 180 },
                 { field: 'SUBWORKFLOWTYPE', title: '子工艺类型', width: 100 }
                ]]
        });
        //分页事件
        $('#ppNot').pagination({
            onSelectPage: function (pageNumber, pageSize) {
//                customizedEasyuiPagination('ppNot'); //定制化分页
                notCardPage.pageSize = pageSize; notCardPage.pageNumber = pageNumber;
                notCardPage.searchData();
            }
        });
        //绑定分页go按钮
        $('#pageGoNot').on("click", function () {
//            var pageNumber = $(this).parents('tr').find('.pagination-num').val();
            var pageNumber = Number($(this).parents('tr').find('.pagination-num').val());
            notCardPage.pageSize = $('#ppNot').find('.pageSize').val() == "" ? 10 : Number($('#ppNot').find('.pageSize').val());
            notCardPage.pageNumber = pageNumber;
            notCardPage.searchData();
        });
        //一键开卡
        $("#btnOneKeyStart").on("click", function () {
            notCardPage.oneKeyStart();
        });
        $('#progressBar').progressbar({
            width: '100%',
            height: '12',
            value: '0',
            text: '{value}%'
        });
    },
    //查询
    searchData: function () {
        var params = {
            PageSize: notCardPage.pageSize,
            PageIndex: notCardPage.pageNumber
        };
        var datas = $("#queryForm").serializeArray();
        $.each(datas, function () {
            params[this.name] = this.value;
        });
        var formData = {
            action: "GetApsShipNotStartContainerInfo",
            params: JSON.stringify(params)
        };
        page.post(page.url, formData, true, function (res) {
            if (!res.Result) {
                displayMessage(res.Message, res.Result);
                return;
            }
            notCardPage.pageTotal = res.RowCount;
            $("#gdContainerInfoNot").datagrid('loadData', { total: res.RowCount, rows: res.DBTable });
        });
    },
    //一键开卡
    oneKeyStart: function () {
        page.disableBtn();
        notCardPage.selectedRows = $("#gdContainerInfoNot").datagrid("getChecked");
        if (notCardPage.selectedRows.length === 0) {
            page.enableBtn();
            displayMessage("请选择开卡数据", false);
            return;
        }
        var isInValid = false;
        for (var i = 0; i < notCardPage.selectedRows.length; i++) {
            if (!isNullOrWhiteSpaceStr(notCardPage.selectedRows[i].IsError)) {
                isInValid = true;
                break;
            }
        }
        if (isInValid) {
            page.enableBtn();
            displayMessage("存在提交过的数据，请重新查询后再操作", false);
            return;
        }
        $("#gdContainerInfoNot").datagrid("showColumn", "IsError"); //显示处理状态
        $("#gdContainerInfoNot").datagrid("showColumn", "Message"); //显示处理结果
        $("#progressBar").show(); //显示总进度条
        notCardPage.setProgressBar(0); //默认为零
        notCardPage.progress = Math.ceil(notCardPage.selectedRows.length / 6); //进度占比
        notCardPage.asyncPost(0); //提交开卡数据（从第一条开始）
    },
    //循环异步提交开卡信息（递归）
    asyncPost: function (index) {
        var formData = {
            action: "OneKeyStartContainerInfo",
            param: JSON.stringify(notCardPage.selectedRows[index])
        };
        $.ajax({
            type: "Post",
            url: page.url,
            data: formData,
            cashe: true,
            async: true,
            dataType: "json",
            beforeSend: function () {
                $.messager.progress({ text: '', msg: '处理中...' });
            },
            success: function (res) {
                $.messager.progress('close');
                notCardPage.setCellsStatus(index, res.Result, res.Message);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $.messager.progress('close');
                notCardPage.setCellsStatus(index, false, "页面提交失败，请刷新后重新提交");
            }
        });
    },
    //设置每行数据的结果状态
    setCellsStatus: function (index, result, message) {
        //更新行消息
        var ix = $("#gdContainerInfoNot").datagrid("getRowIndex", notCardPage.selectedRows[index]);
        if (result) {
            notCardPage.selectedRows[index].IsError = "<span style='color:#1E90FF'>成功</span>";
        } else {
            notCardPage.selectedRows[index].IsError = "<span style='color:#EE2C2C'>失败</span>";
        }
        notCardPage.selectedRows[index].Message = '<span title=' + message + '>' + message + '</span>';
        $('#gdContainerInfoNot').datagrid('updateRow', {
            index: ix,
            row: notCardPage.selectedRows[index]
        });
        $('#gdContainerInfoNot').datagrid('refreshRow', ix); //刷新行
        //如果是最后一条数据，则终止
        if (index + 1 === notCardPage.selectedRows.length) {
            notCardPage.setProgressBar(100);
            displayMessage("处理完成", true);
            page.enableBtn();
            $('#gdContainerInfoNot').datagrid('acceptChanges');
            return;
        }
        notCardPage.setProgressBar(notCardPage.progress * (index + 1)); //设置总进度条
        notCardPage.asyncPost(index + 1); //继续循环下一条数据
    },
    //设置总进度条
    setProgressBar: function (value) {
        $('#progressBar').progressbar('setValue', value);
    },
    //显示自身需要的查询
    showSearch: function () {
        $("#divScanContainer").show();
        $("#divScanOrder").show();
        $("#divProductName").show();
        $("#divContainerName").show();
        $("#divSpecNo").show();
        $("#divPlanDate").show();
    }
};
//已开卡
var beCardPage = {
    pageTotal: 0,
    pageSize: 20,
    pageNumber: 1,
    //初始化页面
    init: function () {
        beCardPage.bind();
        customizedEasyuiPagination('ppEnd'); //定制化分页
    },
    //页面事件绑定
    bind: function () {
        //列表加载
        $("#gdContainerInfoOff").datagrid({
            onLoadSuccess: function (data) {
                $('#ppEnd').pagination('refresh', {	// 改变选项，并刷新分页栏信息
                    total: beCardPage.pageTotal,
                    pageSize: beCardPage.pageSize,
                    pageNumber: beCardPage.pageNumber
                });
                customizedEasyuiPagination('ppEnd'); //定制化分页
            },
            columns: [[
                 { field: 'ck', title: '选择', checkbox: true },
                 { field: 'CONTAINERNAME', title: '批次', width: 180 },
                 { field: 'PRODUCTNAME', title: '件号', width: 150 },
                 { field: 'WORKFLOWNAMEANDREV', title: '工艺', width: 180 },
                 { field: 'WORKFLOWSTEPNAME', title: '工序', width: 150 },
                 { field: 'CONTAINERTYPENAME', title: '批次类型', width: 100 },
                 { field: 'QTY', title: '在制数', width: 60 },
                 { field: 'CREATEDATE', title: '开卡日期', width: 100,
                     formatter: function (value, row, index) {
                         if (!isNullOrWhiteSpaceStr(value)) {
                             return dayjs(value).format('YYYY-MM-DD');
                         }
                     }
                 },
                 { field: 'FACONTAINERNAME', title: '主制批次', width: 150 }
                ]]
        });
        //分页事件
        $('#ppEnd').pagination({
            onSelectPage: function (pageNumber, pageSize) {
                customizedEasyuiPagination('ppEnd'); //定制化分页
                beCardPage.pageSize = pageSize; beCardPage.pageNumber = pageNumber;
                beCardPage.searchData();
            }
        });
        //绑定分页go按钮
        $('#pageGoEnd').on("click", function () {
            var pageNumber = $(this).parents('tr').find('.pagination-num').val();
            beCardPage.pageNumber = pageNumber;
            beCardPage.searchData();
        });
    },
    //查询
    searchData: function () {
        var params = {
            PageSize: beCardPage.pageSize,
            PageIndex: beCardPage.pageNumber
        };
        var datas = $("#queryForm").serializeArray();
        $.each(datas, function () {
            params[this.name] = this.value;
        });
        var formData = {
            action: "GetSubContainerMakeingInfo",
            params: JSON.stringify(params)
        };
        page.post(page.url, formData, true, function (res) {
            if (!res.Result) {
                displayMessage(res.Message, res.Result);
                return;
            }
            beCardPage.pageTotal = res.RowCount;
            $("#gdContainerInfoOff").datagrid('loadData', { total: res.RowCount, rows: res.DBTable });
        });
    },
    //显示自身需要的查询
    showSearch: function () {
        $("#divScanContainer").show();
        $("#divScanOrder").show();
        $("#divProductName").show();
        $("#divContainerName").show();
        $("#divSpecNo").show();
        $("#divPlanDate").hide();
    }
};
//错误日志
var errorPage = {
    pageTotal: 0,
    pageSize: 20,
    pageNumber: 1,
    //初始化页面
    init: function () {
        errorPage.bind();
        customizedEasyuiPagination('ppError'); //定制化分页
    },
    //页面事件绑定
    bind: function () {
        //列表加载
        $("#gdContainerInfoError").datagrid({
            onLoadSuccess: function (data) {
                $('#ppError').pagination('refresh', {	// 改变选项，并刷新分页栏信息
                    total: errorPage.pageTotal,
                    pageSize: errorPage.pageSize,
                    pageNumber: errorPage.pageNumber
                });
                customizedEasyuiPagination('ppError'); //定制化分页
            },
            columns: [[
                 { field: 'CONTAINERNAME', title: '批次', width: 180 },
                 { field: 'WORKFLOWNAMEANDREV', title: '工艺', width: 150 },
                 { field: 'WORKFLOWSTEPNAME', title: '工序', width: 150 },
                 { field: 'ERRORMESSAGE', title: '出错描述', width: 250,
                     formatter: function (value, row, index) {
                         return '<span title=' + value + '>' + value + '</span>';
                     }
                 },
                 { field: 'CREATEDATE', title: '创建日期', width: 100,
                     formatter: function (value, row, index) {
                         if (!isNullOrWhiteSpaceStr(value)) {
                             return dayjs(value).format('YYYY-MM-DD');
                         }
                     }
                 }
                ]]
        });
        //分页事件
        $('#ppError').pagination({
            onSelectPage: function (pageNumber, pageSize) {
                customizedEasyuiPagination('ppError'); //定制化分页
                errorPage.pageSize = pageSize; errorPage.pageNumber = pageNumber;
                errorPage.searchData();
            }
        });
        //绑定分页go按钮
        $('#pageGoError').on("click", function () {
            var pageNumber = $(this).parents('tr').find('.pagination-num').val();
            errorPage.pageNumber = pageNumber;
            errorPage.searchData();
        });
        //导出异常数据
        $('#btnExportError').on("click", function () {
            //判断是否ie浏览器
            if (window.ActiveXObject || "ActiveXObject" in window) {
                displayMessage("请用谷歌浏览器进行导出操作", false);
                return;
            }
            $.messager.progress({ text: '', msg: '处理中...' });
            var xhr = new XMLHttpRequest(); //定义一个XMLHttpRequest对象
            xhr.open("post", page.url, true);
            xhr.responseType = 'blob'; //设置ajax的响应类型为blob
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
            xhr.onload = function ()//当请求完成，响应就绪进入
            {
                if (this.status === 200)//当响应状态码为200时进入
                {
                    var blob = this.response; //获取响应返回的blob对象
                    var a = document.createElement('a'); //在dom树上创建一个a标签
                    var url = window.URL.createObjectURL(new Blob([blob]));
                    a.href = url; //将url赋值给a标签的href属性
                    a.download = decodeURI(xhr.getResponseHeader("Content-Disposition").split('filename=')[1]);
                    a.click(); //主动触发a标签点击事件
                }
                $.messager.progress('close');
            };
            xhr.send("action=ExportErrorInfoToExcel"); //附带参数发送请求
        });
    },
    //查询
    searchData: function () {
        var params = {
            PageSize: errorPage.pageSize,
            PageIndex: errorPage.pageNumber,
            SpecNo: $("#txtSpecNo").textbox("getValue"),
            ContainerName: $("#txtContainerName").textbox("getValue")
        };
        var formData = {
            action: "GetContainerErrorInfo",
            params: JSON.stringify(params)
        };
        page.post(page.url, formData, true, function (res) {
            if (!res.Result) {
                displayMessage(res.Message, res.Result);
                return;
            }
            errorPage.pageTotal = res.RowCount;
            $("#gdContainerInfoError").datagrid('loadData', { total: res.RowCount, rows: res.DBTable });
        });
    },
    //显示自身需要的查询
    showSearch: function () {
        $("#divScanContainer").hide();
        $("#divScanOrder").hide();
        $("#divProductName").hide();
        $("#divContainerName").show();
        $("#divSpecNo").show();
        $("#divPlanDate").hide();
    }
};
$(function () {
    page.init();
});